package com.my.demo.shiro.realms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.demo.pojo.User;
import com.my.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liangyuanshao
 * @date 2021/12/18 - 19:31
 */
public class CustomerRealm extends AuthorizingRealm {

  @Autowired
  UserService userService;

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return null;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    //从传过来的token获取到的用户名
    String principal = (String) token.getPrincipal();
    System.out.println("用户名"+principal);

    //假设是从数据库获得的 用户名，密码
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name", principal);
    User user = userService.getOne(wrapper);


    if(user!=null){
      //返回数据库信息
      SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(),
          ByteSource.Util.bytes(user.getSalt()), this.getName());
      System.out.println(user.getUserName()+"已经认证");
      return simpleAuthenticationInfo;
    }


    return null;
  }

}
